package com.itheima.service.impl;

import com.itheima.common.utils.AliOssUtil;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {
    @Autowired
    private OrderSettingMapper orderSettingMapper;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    /**
     * 模版下载
     */
    @Override
    public void download(String fileName, HttpServletResponse httpServletResponse) {
        //查询数据库
        List<OrderSetting> list = orderSettingMapper.download();
        //基于模版文件创建POI输入流
        try {
            InputStream inputStream = resourceLoader.getResource("classpath:templates/ordersetting_template.xlsx").getInputStream();
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            //填充数据--获得标签页
            XSSFSheet sheet = excel.getSheet("sheet1");
            for (int i = 1; i <= list.size(); i++) {
                //获取行对象
                XSSFRow row = sheet.createRow(i);
                //操作每一列
                if(row.getCell(0) == null){
                    row.createCell(0);
                }
                if(row.getCell(1) == null){
                    row.createCell(1);
                }
                row.getCell(0).setCellValue(list.get(i - 1).getOrderDate());
                row.getCell(1).setCellValue(list.get(i - 1).getNumber());
            }
            //通过输出流把文件下载到客户端
            ServletOutputStream outputStream = httpServletResponse.getOutputStream();
            excel.write(outputStream);
            //关闭流
            outputStream.close();
            excel.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 根据日期修改可预约人数
     */
    @Override
    public void editNumberByOrderDate(OrderSetting orderSetting) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String Date = sdf.format(orderSetting.getOrderDate());
        orderSettingMapper.editNumberByOrderDate(orderSetting.getNumber(), Date);
    }
    /**
     * 根据年月查询对应的预约设置信息
     */
    @Override
    public List<OrderSetting> getOrderSettingByMonth(String date) {
        if(date == null){
            return orderSettingMapper.download();
        }
        //接收的date是字符串类型的例如：2022-1,需要解析这个字符串：
        // 找到这个月的最大值和最小值，因为要进行数据库日期范围查找，最大值和最小值转换成Date类型的数据后，
        // 再去数据库找到这一年这一月的所有数据返回
        String[] split = date.split("-");
        if (split.length == 2) {
            int year = Integer.parseInt(split[0]);
            int month = Integer.parseInt(split[1]);

            // 使用 Calendar 计算当月的最大天数
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.YEAR, year);
            calendar.set(Calendar.MONTH, month - 1); // 月份从0开始
            int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            int minDay = 1;

            // 构造日期范围
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String minDate = sdf.format(new Date(year - 1900, month - 1, minDay)); // 转换为 Date
            String maxDate = sdf.format(new Date(year - 1900, month - 1, maxDay));

            // 调用 Mapper 查询
            List<OrderSetting> list = orderSettingMapper.getByDateRange(minDate, maxDate);
            //遍历list，给每个对象的date字段赋值，赋值规则：orderDate代表的是该年该月的第几天
            for (OrderSetting orderSetting : list) {
                // 将 Date 类型的 orderDate 转换为 String 类型
                Date orderDate = orderSetting.getOrderDate();
                if (orderDate != null) {
                    String formattedOrderDate = sdf.format(orderDate); // 格式化为字符串
                    String[] split1 = formattedOrderDate.split("-");
                    int day = Integer.parseInt(split1[2]);
                    orderSetting.setDate(day);
                }
            }
            return list;
        }
        return null;
    }
    /**
     * 文件上传Excel
     */
    @Override
    public void upload(MultipartFile excelFile) {
        try {
            // 获取原始文件名
            String originalFileName = excelFile.getOriginalFilename();
            // 获取文件扩展名
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            // 生成唯一的文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;
            // 获取文件字节数组
            byte[] bytes = excelFile.getBytes();
            // 使用AliOssUtil上传文件
            aliOssUtil.upload(bytes, newFileName);
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
}
